import heapq

from querier.esquerier import ElasticSearchQuerier


WORDCLOUD_TOP_N = 100


class BrandWordCloudQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type):
        super(BrandWordCloudQuerier, self).__init__(None, None, None)
        self.es = es
        self.index = index
        self.doc_type = doc_type

    def _build_query(self, args): pass

    def _build_result(self, es_result, param): pass

    def search(self, args):
        id_ = args['brand']
        res = self.es.get(index=self.index, doc_type=self.doc_type, id=id_)
        if res['found']:
            brand = res['_source']['brand']
            biz_code = res['_source']['biz_code']
            biz_name = res['_source']['biz_name']
            class1_id = res['_source']['class1_id']
            class1_name = res['_source']['class1_name']
            keywords = res['_source']['keywords'][0:WORDCLOUD_TOP_N]
            weight = res['_source']['weight'][0:WORDCLOUD_TOP_N]
            len_keywords = len(keywords)
            len_weight = len(weight)
            length = len_keywords if len_keywords <= len_weight else len_weight
            ret = [{"text": keywords[i], "weight": weight[i]} for i in range(0, length)]
            return {
                "brand": brand,
                "biz_code": biz_code,
                "biz_name": biz_name,
                "class1_id": class1_id,
                "class1_name": class1_name,
                "keywords": ret
            }
        return {'message': 'brand=%s not found.' % id_}
